
__all__ = ['format']

import json
from pathlib import Path


text = Path(r"data\permissions.json").read_text(encoding="utf-8")
data = json.loads(text)
def check_duplicates(permissions):
    '''
        检查是否有重复
    '''
    s = set()
    duplicates = []
    for permission in permissions:
        code = permission['code']
        if code in s:
            duplicates.append(permission)
        else:
            s.add(code)
    return duplicates

def remove_duplicates(permissions):
    '''
        移除重复的权限
    '''
    codes = set()
    ls = []
    for permission in permissions:
        code = permission['code']
        if code not in codes:
            codes.add(code)
            ls.append(permission)
    return ls

def sort_by_code_level(permissions):
    '''
        排序，先按 code 的层级排序，之后按名称排序
    '''
    return sorted(permissions, key=lambda x: (x['code'].count(':'), x['name']))
def transform(perm):
    code = perm['code']
    if code in data:
        item = data[code]
        for key, value in item.items():
            perm[key] = value
def format(permissions):
    '''
        - 父节点会在前
        - 移除重复的权限
        - 默认值处理
    '''
    permissions = sort_by_code_level(remove_duplicates(permissions))
    for permission in permissions:
        transform(permission)

    return permissions